package com.demo.springcloud.alibaba.nacos;

import java.text.MessageFormat;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import jakarta.annotation.PreDestroy;
import jakarta.annotation.Resource;

/**
 * SpringcloudAlibabaNacosConsumer
 * 
 * @author xiaojianhx
 * @version V1.0.0 $ 2023-11-23 13:17:55 init ---- xiaojianhx
 */
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
@Controller
public class SpringcloudAlibabaNacosConsumer {

    public static void main(String[] args) {
        SpringApplication.run(SpringcloudAlibabaNacosConsumer.class, args);
    }

    @PreDestroy
    public void destroy() {
        System.out.println("pre destroy running....");
    }

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private ProviderService providerService;

    @ResponseBody
    @RequestMapping(value = "/echo1/{str}")
    public String echo1(@PathVariable String str) {

        var instance = loadBalancerClient.choose(ProviderConstants.SERVICE_ID);
        var url = "http://{0}:{1,number,#}/echo/{2}";
        url = MessageFormat.format(url, instance.getHost(), instance.getPort(), str);
        System.out.println(instance.getMetadata());

        System.out.println(url);
        var result = restTemplate.getForEntity(url, String.class).getBody();

        System.out.println(url + " --> " + result);

        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/echo2/{str}")
    public String echo2(@PathVariable String str) {
        return providerService.echo(str);
    }
}